<!--------------------------------
 - @Author: Your Name
 - @LastEditor: Your Name
 - @LastEditTime: 2025-11-07
 - Copyright © 2025 Your Name
 --------------------------------->

<template>
  <CommonPage>
    <template #action>
      <NButton v-permission="'AddProject'" type="primary" @click="handleAdd()">
        <i class="i-material-symbols:add mr-4 text-18" />
        创建项目
      </NButton>
    </template>

    <MeCrud
      ref="$table"
      v-model:query-items="queryItems"
      :scroll-x="1200"
      :columns="columns"
      :get-data="api.read"
    >
      <MeQueryItem label="项目名称" :label-width="70">
        <n-input
          v-model:value="queryItems.name"
          type="text"
          placeholder="请输入项目名称"
          clearable
        />
      </MeQueryItem>

      <MeQueryItem label="项目分类" :label-width="70">
        <n-select
          v-model:value="queryItems.categoryId"
          :options="categories"
          label-field="name"
          value-field="id"
          clearable
          filterable
          placeholder="请选择项目分类"
        />
      </MeQueryItem>

      <MeQueryItem label="项目状态" :label-width="70">
        <n-select
          v-model:value="queryItems.status"
          :options="projectStatusOptions"
          label-field="name"
          value-field="value"
          clearable
          placeholder="请选择项目状态"
        />
      </MeQueryItem>

      <MeQueryItem label="负责人" :label-width="70">
        <n-input
          v-model:value="queryItems.owner"
          type="text"
          placeholder="请输入负责人"
          clearable
        />
      </MeQueryItem>
    </MeCrud>

    <MeModal ref="modalRef" width="600px">
      <n-form
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="100"
        :model="modalForm"
        :disabled="modalAction === 'view'"
      >
        <n-form-item
          label="项目名称"
          path="name"
          :rule="{
            required: true,
            message: '请输入项目名称',
            trigger: ['blur'],
          }"
        >
          <n-input v-model:value="modalForm.name" />
        </n-form-item>

        <n-form-item
          label="项目分类"
          path="categoryId"
        >
          <n-cascader
            v-model:value="cascaderCategoryValue"
            :options="categoryCascaderOptions"
            label-field="name"
            value-field="id"
            children-field="children"
            placeholder="请选择项目分类"
            filterable
            clearable
            @update:value="handleCascaderChange"
          />
        </n-form-item>

        <n-form-item
          label="项目描述"
          path="description"
        >
          <n-input
            v-model:value="modalForm.description"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入项目描述"
          />
        </n-form-item>

        <n-form-item
          label="项目状态"
          path="status"
        >
          <n-select
            v-model:value="modalForm.status"
            :options="projectStatusOptions"
            label-field="name"
            value-field="value"
            placeholder="请选择项目状态"
          />
        </n-form-item>

        <n-form-item
          label="负责人"
          path="ownerId"
        >
          <n-select
            v-model:value="modalForm.ownerId"
            :options="users"
            label-field="description"
            value-field="id"
            placeholder="请选择负责人"
            filterable
            remote
            :loading="userLoading"
            :searchable="true"
            clearable
            @search="handleUserSearch"
          />
        </n-form-item>

        <n-form-item label="开始时间" path="startDate">
          <NDatePicker
            v-model:value="modalForm.startDate"
            type="date"
            placeholder="请选择开始时间"
          />
        </n-form-item>

        <n-form-item label="结束时间" path="endDate">
          <NDatePicker
            v-model:value="modalForm.endDate"
            type="date"
            placeholder="请选择结束时间"
          />
        </n-form-item>

        <n-form-item label="项目可见性" path="visibility">
          <n-select
            v-model:value="modalForm.visibility"
            :options="[
              { label: '公开', value: 'PUBLIC' },
              { label: '私有', value: 'PRIVATE' },
              { label: '指定用户', value: 'SPECIFIC' },
            ]"
            placeholder="请选择项目可见性"
          />
        </n-form-item>

        <n-form-item label="启用状态" path="enable">
          <NSwitch v-model:value="modalForm.enable">
            <template #checked>
              启用
            </template>
            <template #unchecked>
              停用
            </template>
          </NSwitch>
        </n-form-item>
      </n-form>
    </MeModal>
  </CommonPage>
</template>

<script setup>
import { NButton, NDatePicker, NSwitch, NTag } from 'naive-ui'
import { MeCrud, MeModal, MeQueryItem } from '@/components'
import { useCrud } from '@/composables'
import { formatDateTime } from '@/utils'
import api from './api'

defineOptions({ name: 'ProjectMgt' })

const $table = ref(null)
/** QueryBar筛选参数（可选） */
const queryItems = ref({})

onMounted(() => {
  $table.value?.handleSearch()
})

// 项目分类选项（支持层级结构）
const categories = ref([])
const categoryCascaderOptions = ref([])
const cascaderCategoryValue = ref([]) // 级联选择器的值（路径数组）

// 生成级联选择器的完整路径数组
function getCategoryPath(categoryId) {
  if (!categoryId || !categories.value || categories.value.length === 0) {
    return []
  }

  // 查找从根节点到目标节点的完整路径
  const findPath = (targetId, currentId = null, path = []) => {
    if (currentId && currentId !== targetId) {
      path = [...path, currentId]
    }

    if (currentId === targetId) {
      return path
    }

    // 查找所有可能的根节点
    for (const category of categories.value) {
      if (!category.parentId || category.parentId === null) {
        const foundPath = findPath(targetId, category.id, path)
        if (foundPath) {
          return foundPath
        }
      }
    }

    return null
  }

  return findPath(categoryId) || []
}

// 处理级联选择器变化
function handleCascaderChange(value) {
  console.log('级联选择器变化:', value)
  cascaderCategoryValue.value = value
  // 设置最终的分类ID（路径的最后一个值）
  if (value && value.length > 0) {
    modalForm.categoryId = value[value.length - 1]
  }
  else {
    modalForm.categoryId = null
  }
}

function buildCategoryTree(data) {
  console.log('开始构建分类树，原始数据:', data)

  if (!data || !Array.isArray(data) || data.length === 0) {
    console.log('数据无效，返回空数组')
    return []
  }

  try {
    // 创建节点映射表和根节点数组
    const nodeMap = new Map()
    const rootNodes = []

    // 第一步：为所有数据项创建节点对象
    data.forEach((item) => {
      // 验证必要字段
      if (!item || !item.id || item.id === '') {
        console.warn('跳过无效的分类数据项:', item)
        return
      }

      // 创建节点对象
      const node = {
        id: item.id,
        name: item.name || '',
        description: item.description || '',
        children: [],
      }

      nodeMap.set(item.id, node)
    })

    console.log('创建了', nodeMap.size, '个节点')

    // 第二步：建立父子关系
    data.forEach((item) => {
      if (!item || !item.id)
        return

      const currentNode = nodeMap.get(item.id)
      if (!currentNode)
        return

      // 检查父节点
      const parentId = item.parentId
      if (parentId && parentId !== null && parentId !== '' && nodeMap.has(parentId)) {
        // 找到父节点，将当前节点添加到父节点的children中
        const parentNode = nodeMap.get(parentId)
        parentNode.children.push(currentNode)
        console.log(`节点 ${item.name}(${item.id}) 连接到父节点`)
      }
      else {
        // 没有父节点或父节点不存在，作为根节点
        rootNodes.push(currentNode)
        console.log(`节点 ${item.name}(${item.id}) 作为根节点`)
      }
    })

    console.log('构建完成，根节点数量:', rootNodes.length)
    console.log('构建后的树形数据:', JSON.stringify(rootNodes, null, 2))

    return rootNodes
  }
  catch (error) {
    console.error('构建树形结构时发生错误:', error)
    return []
  }
}

api.getProjectCategories().then(({ data = [] }) => {
  console.log('原始项目分类数据:', data)
  categories.value = data
  const treeData = buildCategoryTree(data)
  console.log('构建后的树形数据:', treeData)
  categoryCascaderOptions.value = treeData // 直接赋值，确保数据正确
  console.log('级联选择器数据:', categoryCascaderOptions.value)
})

// 项目状态选项
const projectStatusOptions = ref([
  { name: '规划中', value: 'PLANNING' },
  { name: '进行中', value: 'IN_PROGRESS' },
  { name: '已完成', value: 'COMPLETED' },
  { name: '已暂停', value: 'PAUSED' },
  { name: '已取消', value: 'CANCELLED' },
])

// 用户列表（用于选择负责人）
const users = ref([])
const userLoading = ref(false)

// 获取用户列表
function loadUsers(search = '') {
  userLoading.value = true
  api.getUsers({ username: search }).then(({ data = [] }) => {
    users.value = data
    userLoading.value = false
  }).catch(() => {
    userLoading.value = false
  })
}

// 初始化加载用户
loadUsers()

// 搜索用户
function handleUserSearch(search) {
  if (search === undefined)
    return
  loadUsers(search)
}

const {
  modalRef,
  modalFormRef,
  modalForm,
  modalAction,
  handleAdd,
  handleDelete,
  handleOpen,
  handleSave,
} = useCrud({
  name: '项目',
  initForm: {
    name: '',
    description: '',
    categoryId: null,
    status: 'PLANNING',
    ownerId: null,
    startDate: null,
    endDate: null,
    visibility: 'PRIVATE',
    enable: true,
  },
  doCreate: async (data) => {
    console.log('创建项目数据:', data)

    // 格式化日期字段，确保后端接收正确格式
    const formattedData = { ...data }
    if (formattedData.startDate && typeof formattedData.startDate === 'number') {
      formattedData.startDate = formatDateTime(formattedData.startDate)
    }
    if (formattedData.endDate && typeof formattedData.endDate === 'number') {
      formattedData.endDate = formatDateTime(formattedData.endDate)
    }

    console.log('格式化后的数据:', formattedData)
    return await api.create(formattedData)
  },
  doDelete: api.delete,
  doUpdate: async (data) => {
    console.log('更新项目数据:', data)

    // 格式化日期字段，确保后端接收正确格式
    const formattedData = { ...data }
    if (formattedData.startDate && typeof formattedData.startDate === 'number') {
      formattedData.startDate = formatDateTime(formattedData.startDate)
    }
    if (formattedData.endDate && typeof formattedData.endDate === 'number') {
      formattedData.endDate = formatDateTime(formattedData.endDate)
    }

    console.log('格式化后的数据:', formattedData)
    return await api.update(formattedData)
  },
  onOpen: ({ action, row }) => {
    // 模态框打开时，设置级联选择器的值
    if (action === 'edit' && row && row.categoryId) {
      // 等待数据加载完成后设置级联选择器值
      setTimeout(() => {
        const path = getCategoryPath(row.categoryId)
        console.log('编辑模式设置级联路径:', row.categoryId, path)
        cascaderCategoryValue.value = path
      }, 100)
    }
    else if (action === 'add') {
      // 新增模式清空级联选择器
      cascaderCategoryValue.value = []
    }
  },
  refresh: () => $table.value?.handleSearch(),
})

const columns = [
  { title: '项目名称', key: 'name', width: 200, ellipsis: { tooltip: true } },
  {
    title: '项目分类',
    key: 'category',
    width: 150,
    ellipsis: { tooltip: true },
    render: (row) => {
      const category = categories.value.find(item => item.id === row.categoryId)
      return category ? h(NTag, { type: 'info' }, { default: () => category.name }) : '未分类'
    },
  },
  {
    title: '项目描述',
    key: 'description',
    width: 250,
    ellipsis: { tooltip: true },
  },
  {
    title: '项目状态',
    key: 'status',
    width: 120,
    render: (row) => {
      const status = projectStatusOptions.value.find(item => item.value === row.status)
      return status ? h(NTag, { type: getStatusTagType(row.status) }, { default: () => status.name }) : '未知'
    },
  },
  {
    title: '负责人',
    key: 'owner',
    width: 120,
    render: (row) => {
      const user = users.value.find(item => item.id === row.ownerId)
      return user ? (user.description || user.name) : '未知'
    },
  },
  {
    title: '开始时间',
    key: 'startDate',
    width: 150,
    render(row) {
      return h('span', row.startDate ? formatDateTime(new Date(row.startDate)) : '-')
    },
  },
  {
    title: '结束时间',
    key: 'endDate',
    width: 150,
    render(row) {
      return h('span', row.endDate ? formatDateTime(new Date(row.endDate)) : '-')
    },
  },
  {
    title: '可见性',
    key: 'visibility',
    width: 100,
    render: (row) => {
      const visibilityMap = {
        PUBLIC: '公开',
        PRIVATE: '私有',
        SPECIFIC: '指定用户',
      }
      return h(NTag, { type: 'success' }, { default: () => visibilityMap[row.visibility] || '未知' })
    },
  },
  {
    title: '状态',
    key: 'enable',
    width: 100,
    render: row =>
      h(
        NSwitch,
        {
          size: 'small',
          rubberBand: false,
          value: row.enable,
          loading: !!row.enableLoading,
          onUpdateValue: () => handleEnable(row),
        },
        {
          checked: () => '启用',
          unchecked: () => '停用',
        },
      ),
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
    render(row) {
      return h('span', formatDateTime(row.createTime))
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 300,
    align: 'right',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            class: 'ml-12px',
            onClick: () => handleView(row),
          },
          {
            default: () => '查看',
            icon: () => h('i', { class: 'i-carbon:document-view text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            class: 'ml-12px',
            onClick: () => {
              console.log('编辑按钮被点击', row)
              handleEdit(row)
            },
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-material-symbols:edit-outline text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },
]

/**
 * 根据项目状态返回对应的标签类型
 */
function getStatusTagType(status) {
  const statusTypeMap = {
    PLANNING: 'warning',
    IN_PROGRESS: 'info',
    COMPLETED: 'success',
    PAUSED: 'warning',
    CANCELLED: 'error',
  }
  return statusTypeMap[status] || 'default'
}

async function handleEnable(row) {
  row.enableLoading = true
  try {
    await api.update({ id: row.id, enable: !row.enable })
    row.enableLoading = false
    $message.success('操作成功')
    $table.value?.handleSearch()
  }
  catch (error) {
    console.error(error)
    row.enableLoading = false
  }
}

function handleView(row) {
  handleOpen({ action: 'view', title: '查看项目', row })
}

function handleEdit(row) {
  // 确保编辑数据的完整性，日期字段需要处理为时间戳格式
  const editRow = {
    ...row,
    categoryId: row.categoryId || null,
    ownerId: row.ownerId || null,
    // 处理日期格式：后端返回字符串，前端日期选择器期望时间戳
    startDate: row.startDate ? new Date(row.startDate).getTime() : null,
    endDate: row.endDate ? new Date(row.endDate).getTime() : null,
  }

  handleOpen({ action: 'edit', title: '编辑项目', row: editRow })
}
</script>
